package com.dataManager.www.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dataManager.www.entity.Block;
import com.dataManager.www.entity.Transaction;
import com.dataManager.www.entity.User;
import com.dataManager.www.service.UserService;
import com.dataManager.www.utils.CheckUtils;
import com.dataManager.www.utils.SystemCode;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/sys/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 跳转到首页
     * @return
     */
    @RequestMapping(value = "index")
    public String index() {
        return "../index";
    }

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping(value = "login")
    public String login(){
        return "login-1";
    }

    /**
     * 跳转到用户设置页面
     * @return
     */
    @RequestMapping(value = "update")
    public String update(){
        return "user-setting";
    }

    /**
     * 根据不同权限跳转到不同页面
     * 普通用户跳转到容量申请
     * 管理员跳转到容量审批
     * @param request
     * @return
     */
    @RequestMapping(value = "updateDiskSize")
    public String UpdateDiskSize(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if(user.getRole().equals(SystemCode.ADMIN_USER)) return "user-approval-disksize";
        else if(user.getRole().equals(SystemCode.NORMAL_USER))return "user-apply-disksize";
        else return "user-apply-disksize";
    }

    /**
     * 跳转到编辑页面
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "edit")
    public String register(RedirectAttributes redirectAttributes) {
        return "table/edit";
    }

    /**
     * 编辑用户信息
     * @param username
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "editUser/{username}")
    public String editUser(@PathVariable String username,RedirectAttributes redirectAttributes){
        Map<String,String> map = new HashMap<String, String>();
        map.put("username",username);
        User user= userService.get(map);
        System.out.println(user.toString());
        redirectAttributes.addFlashAttribute("editUser", user);
        return "redirect:/sys/user/edit";
    }

    /**
     * 用户发出申请容量的请求
     * @param applySize
     * @param request
     * @return
     */
    @RequestMapping(value = "doApplyDiskSize")
    @ResponseBody
    public String applyDiskSize(@RequestParam double applySize,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        user.setApplySize(applySize);
        user.setStatus("申请容量中");
        userService.update(user);
        return SystemCode.SUCCESS;
    }

    /**
     * 列出所有用户（AJAX）
     * @return
     */
    @RequestMapping(value = "listUsers")
    @ResponseBody
    public Map<String, Object> listUser(){
        List<User> userList = userService.listAll();
        Map<String, Object> tableJson = new HashMap<String, Object>();
        tableJson.put("code",0);
        tableJson.put("msg","");
        tableJson.put("count",userList.size());
        tableJson.put("data",userList);
        return tableJson;
    }

    /**
     * 通常登录方法（暂时弃用）
     * @param user
     * @param request
     * @return
     */
    @RequestMapping(value = "doLogin")
    public String login(User user,HttpServletRequest request) {
        System.out.println(user.getUsername()+"  "+user.getPassword());
        HashMap userMap = new HashMap();
        userMap.put("username",user.getUsername());
        userMap.put("password",user.getPassword());
        User loginUser =userService.get(userMap);
        if (null!=loginUser){
            request.getSession().setAttribute("user",loginUser);
            System.out.println("登录用户："+request.getSession().getAttribute("user")==null);
            return "forward:/sys/user/index";
        }
        else
            return "login-1";
    }

    /**
     * 登录用户（AJAX）
     * @param username
     * @param password
     * @param captcha
     * @param request
     * @return
     */
    @RequestMapping(value = "doLoginAjax")
    @ResponseBody
    public String loginAjax(@RequestParam String username, @RequestParam String password, @RequestParam String captcha, HttpServletRequest request) {
        System.out.println("AJAX");
        if(!captcha.equals(request.getSession().getAttribute("sRand"))){
            return SystemCode.CAPTCHA_ERROR;
        }
        HashMap<String,Object> userMap = new HashMap<String,Object>();
        if(CheckUtils.checkEmail(username))userMap.put("email",username);
        else if(CheckUtils.cheakPhone(username))userMap.put("phone",username);
        else userMap.put("username",username);
        userMap.put("password",password);
        User loginUser =userService.get(userMap);
        if (null!=loginUser){
            request.getSession().setAttribute("user",loginUser);
            return SystemCode.SUCCESS;
        }
        else
            return SystemCode.PASSWORD_ERROR;
    }

    /**
     * 登出用户（AJAX）
     * @param request
     * @return
     */
    @RequestMapping(value = "doLogout")
    public String logout(HttpServletRequest request){
        //遍历所有session中的状态
        Enumeration em = request.getSession().getAttributeNames();
        while(em.hasMoreElements()){
            //移除
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        return "login-1";
    }

    /**
     * 更新用户信息（AJAX）
     * @param user
     * @param request
     * @return
     */
    @RequestMapping(value = "doUpdateAjax")
    @ResponseBody
    public String updateAjax(@RequestBody User user,HttpServletRequest request){
        System.out.println("update:"+user.toString());
        User loginUser = (User) request.getSession().getAttribute("user");
        User newUser = userService.update(user);
        if(null!=newUser){
            if(newUser.getId().equals(loginUser.getId())){
                request.getSession().setAttribute("user",newUser);
            }
            return SystemCode.SUCCESS;
        }
        return SystemCode.ERROR;
    }

    /**
     * 重置用户密码（AJAX）
     * @param oldPassword
     * @param newPassword
     * @param request
     * @return
     */
    @RequestMapping(value = "doResetPwByOldAjax")
    @ResponseBody
    public String resetPasswordByOldPassword(@RequestParam String oldPassword,@RequestParam String newPassword, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if(oldPassword.equals(user.getPassword())){
            user.setPassword(newPassword);
            User newUser = userService.update(user);
            if(null!=newUser){
                request.getSession().setAttribute("user",newUser);
                return SystemCode.SUCCESS;
            }
        }
        return SystemCode.ERROR;

    }

    /**
     * 审批通过用户的容量申请
     * @param user
     * @return
     */
    @RequestMapping(value = "doAllowApplyDiskSize")
    @ResponseBody
    public User allowApply(@RequestBody User user){
        user.setDiskSize(user.getDiskSize()+user.getApplySize());
        user.setApplySize(0);
        user.setStatus("正常");
        userService.update(user);
        return user;
    }


    /**
     * 通过挖矿获得容量
     * @param request
     * @return
     */
    @RequestMapping(value = "mineSize")
    @ResponseBody
    public String mineSize(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8090/mine";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("changeSize", "30");
        map.add("userId",user.getId()+"");
        HttpEntity<MultiValueMap<String, String>> request1 = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( url, request1 , String.class );
        System.out.println(response.getBody());
        return SystemCode.SUCCESS;
    }

    /**
     * 计算挖矿的容量所得
     * @param request
     * @return
     */
    @RequestMapping(value = "calculateSize")
    @ResponseBody
    public String calculateSize(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8090/scan";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        System.out.println(response.getBody());
        
        Gson gson = new Gson();
        Block[] blocks = gson.fromJson(response.getBody(), Block[].class);
        double mineSize = 0.0;
        for (Block block : blocks) {
            List<Transaction> transactionList = block.getTransactions();
            Long userId = null;
            double changeSize = 0;
            for (Transaction transaction : transactionList) {
                System.out.println(transaction.toString());
                if (transaction.getId().equals("userId")) {
                    userId = Long.parseLong(transaction.getBusinessInfo());
                    System.out.println(userId);
                }
                if (transaction.getId().equals("changeSize")) {
                    changeSize = Double.parseDouble(transaction.getBusinessInfo());
                    System.out.println(changeSize);
                }
            }
            if(userId!=null){
                if (userId.equals(user.getId())) {
                    mineSize = mineSize+changeSize;
                }
            }
        }
        System.out.println("挖矿获得的总量:"+mineSize);
        user.setMineSize(mineSize);
        userService.update(user);
        request.getSession().setAttribute("user",user);
        return user.getMineSize()+"";
    }

    @RequestMapping(value = "doRegister")
    @ResponseBody
    public String doRegister(@RequestBody User user){
        user.setMineSize(0);
        user.setStatus("正常");
        user.setRole(SystemCode.NORMAL_USER);
        user.setApplySize(0);
        user.setDiskSize(1000);
        user.setMineSize(0);
        userService.add(user);
        return SystemCode.SUCCESS;
    }
}
